<?php
declare(strict_types=1);

namespace app\controller\merchant;

use app\BaseController;
use app\model\{Order, CouponOrder, User, UserPackage};
use think\facade\{Db, Log};
use think\Request;

class StatisticsController extends BaseController
{
    /**
     * 获取订单统计数据
     */
    public function orderStats(Request $request)
    {
        try {
            $merchant_id = $request->merchant_id;
            $start_date = $request->get('start_date', date('Y-m-d', strtotime('-30 days')));
            $end_date = $request->get('end_date', date('Y-m-d'));
            
            // 按日期统计订单数据
            $daily_stats = Order::where([
                    ['merchant_id', '=', $merchant_id],
                    ['create_time', 'between time', [$start_date, $end_date]]
                ])
                ->field([
                    "DATE_FORMAT(create_time, '%Y-%m-%d') as date",
                    'count(*) as order_count',
                    'sum(fee_actual) as total_fee',
                    'sum(merchant_profit) as total_profit'
                ])
                ->group('date')
                ->select();
            
            // 订单状态分布
            $status_stats = Order::where([
                    ['merchant_id', '=', $merchant_id],
                    ['create_time', 'between time', [$start_date, $end_date]]
                ])
                ->field([
                    'status',
                    'count(*) as count'
                ])
                ->group('status')
                ->select();
            
            // 快递公司分布
            $company_stats = Order::where([
                    ['merchant_id', '=', $merchant_id],
                    ['create_time', 'between time', [$start_date, $end_date]]
                ])
                ->field([
                    'company_code',
                    'count(*) as count',
                    'sum(fee_actual) as total_fee'
                ])
                ->group('company_code')
                ->select();
            
            return json(['code' => 0, 'msg' => '获取成功', 'data' => [
                'daily' => $daily_stats,
                'status' => $status_stats,
                'company' => $company_stats
            ]]);
        } catch (\Exception $e) {
            Log::error('获取订单统计数据失败: ' . $e->getMessage());
            return json(['code' => 1, 'msg' => $e->getMessage()]);
        }
    }

    /**
     * 获取用户统计数据
     */
    public function userStats(Request $request)
    {
        try {
            $merchant_id = $request->merchant_id;
            $start_date = $request->get('start_date', date('Y-m-d', strtotime('-30 days')));
            $end_date = $request->get('end_date', date('Y-m-d'));
            
            // 按日期统计新增用户
            $daily_stats = User::where([
                    ['merchant_id', '=', $merchant_id],
                    ['create_time', 'between time', [$start_date, $end_date]]
                ])
                ->field([
                    "DATE_FORMAT(create_time, '%Y-%m-%d') as date",
                    'count(*) as user_count'
                ])
                ->group('date')
                ->select();
            
            // 用户活跃度分析
            $active_stats = Order::where([
                    ['merchant_id', '=', $merchant_id],
                    ['create_time', 'between time', [$start_date, $end_date]]
                ])
                ->field([
                    'user_id',
                    'count(*) as order_count',
                    'sum(fee_actual) as total_fee'
                ])
                ->group('user_id')
                ->having('order_count >= 1')
                ->select();
            
            // 会员分布
            $member_stats = UserPackage::where([
                    ['merchant_id', '=', $merchant_id],
                    ['create_time', 'between time', [$start_date, $end_date]]
                ])
                ->field([
                    'package_id',
                    'count(*) as count'
                ])
                ->group('package_id')
                ->select();
            
            return json(['code' => 0, 'msg' => '获取成功', 'data' => [
                'daily' => $daily_stats,
                'active' => $active_stats,
                'member' => $member_stats
            ]]);
        } catch (\Exception $e) {
            Log::error('获取用户统计数据失败: ' . $e->getMessage());
            return json(['code' => 1, 'msg' => $e->getMessage()]);
        }
    }

    /**
     * 获取优惠券统计数据
     */
    public function couponStats(Request $request)
    {
        try {
            $merchant_id = $request->merchant_id;
            $start_date = $request->get('start_date', date('Y-m-d', strtotime('-30 days')));
            $end_date = $request->get('end_date', date('Y-m-d'));
            
            // 按日期统计领券订单
            $daily_stats = CouponOrder::where([
                    ['merchant_id', '=', $merchant_id],
                    ['create_time', 'between time', [$start_date, $end_date]]
                ])
                ->field([
                    "DATE_FORMAT(create_time, '%Y-%m-%d') as date",
                    'count(*) as order_count',
                    'sum(order_amount) as total_amount',
                    'sum(merchant_commission) as total_commission'
                ])
                ->group('date')
                ->select();
            
            // 业务类型分布
            $business_stats = CouponOrder::where([
                    ['merchant_id', '=', $merchant_id],
                    ['create_time', 'between time', [$start_date, $end_date]]
                ])
                ->field([
                    'business_type',
                    'count(*) as count',
                    'sum(order_amount) as total_amount'
                ])
                ->group('business_type')
                ->select();
            
            return json(['code' => 0, 'msg' => '获取成功', 'data' => [
                'daily' => $daily_stats,
                'business' => $business_stats
            ]]);
        } catch (\Exception $e) {
            Log::error('获取优惠券统计数据失败: ' . $e->getMessage());
            return json(['code' => 1, 'msg' => $e->getMessage()]);
        }
    }
} 